import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:paint/custom_paint/custom_paint0.dart';
import 'package:paint/gradient_circular_progress/page.dart' as gc;

void main() {
  runApp(
    MaterialApp(
        home: Scaffold(
      body: Page(),
    )),
  );
}

class Page extends StatefulWidget {
  const Page({Key key}) : super(key: key);

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> {
  GlobalKey rootWidgetKey = GlobalKey();

  Future<Uint8List> _capturePNG() async {
    try {
      RenderRepaintBoundary boundary =
          rootWidgetKey.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 10.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      return byteData.buffer.asUint8List();
    } catch (e) {
      print(e);
    }
    return null;
  }

  void _captureAndSave() async {
    var imageData = await _capturePNG();
    final result = await ImageGallerySaver.saveImage(imageData);
    print("result = $result");
  }

  @override
  Widget build(BuildContext context) {
    var container = Container(
      child: Stack(
        children: <Widget>[
          // RepaintBoundary(
          //   key: rootWidgetKey,
          //   child: ListView.separated(
          //     separatorBuilder: (c, i) => SizedBox(
          //       height: 10,
          //     ),
          //     itemBuilder: (BuildContext context, int index) {
          //       return gc.GradientCircularProgressRoute();
          //     },
          //     itemCount: 100,
          //   ),
          // ),
          RepaintBoundary(
            key: rootWidgetKey,
            child: ListView.separated(
              separatorBuilder: (c, i) => SizedBox(
                height: 10,
              ),
              itemBuilder: (BuildContext context, int index) {
                return CustomPaintRoute();
              },
              itemCount: 100,
            ),
          ),
          // Positioned(
          //   child: Image.me,
          // ),
          Positioned(
            child: MaterialButton(
              color: Colors.red,
              child: Text('截图'),
              onPressed: () {
                print('截图');
                _captureAndSave();
              },
            ),
            right: 10,
            bottom: 10,
          ),
        ],
      ),
    );

    return container;
  }
}
